package com.itcoon.cloud.framework.security.handler;

import com.itcoon.cloud.framework.ex.register.IErrorCodeRegister;
import com.itcoon.cloud.framework.security.ex.SecurityResponseEnum;
import com.itcoon.cloud.framework.utils.SpringUtils;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * created in 2021/4/7
 */
public class DefaultAccessDeniedHandler implements AccessDeniedHandler {

    private static final Logger log = LoggerFactory.getLogger(DefaultAccessDeniedHandler.class);

    private final IErrorCodeRegister errorCodeRegister;

    public DefaultAccessDeniedHandler(IErrorCodeRegister errorCodeRegister) {
        this.errorCodeRegister = errorCodeRegister;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) {
        log.warn(ex.getMessage());
        if (!response.isCommitted()) {
            SecurityResponseEnum errorCode = SecurityResponseEnum.ACCESS_FORBIDDEN;
            String message = errorCodeRegister.getMessage(SpringUtils.getApplicationName(), errorCode.getCode());
            ApiResponse<Void> apiResponse = ApiResponse.error(errorCode.getCode(), message);
            ApiResponseUtils.writeJsonResponse(response, apiResponse, HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
}
